<template>
  <base-breadcrumb v-loading="loading">
    <a-card class="mb20">
      <titleName
        ref="box"
        title="基本信息"
      />
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-model-item
              label="所属单位："
              prop="projectId"
            >
              <org-tree-select
                :is-auto-select-first="$route.query.pageType === 'add'"
                is-need-auth
                :is-query-projec-detail="false"
                check-strictly
                @select="selectOrg"
                v-model="form.projectId"
              />
            </a-form-model-item>
          </a-col>
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="分公司名称："-->
          <!--              prop="branchComId"-->
          <!--            >-->
          <!--              <SelectSubCompany-->
          <!--                v-model="form.branchComId"-->
          <!--                placeholder="请选择"-->
          <!--                :autoSelected="this.$route.query.pageType === 'edit'?false:true"-->
          <!--                @selectChange="-->
          <!--                  projectDeptOrgId = form.branchComId-->
          <!--                  form.speaker = undefined-->
          <!--                "-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="所属项目："-->
          <!--              prop="projectId"-->
          <!--            >-->
          <!--              <SelectProject-->
          <!--                :autoSelected="false"-->
          <!--                :isPostpone="true"-->
          <!--                v-model="form.projectId"-->
          <!--                allowClear-->
          <!--                placeholder="请选择"-->
          <!--                :form="form"-->
          <!--                :is-edit="form.id !== null"-->
          <!--                key-value="branchComId"-->
          <!--                @change="changeProject"-->
          <!--              />-->

          <!--              &lt;!&ndash; <SelectProject v-model="form.projectId" placeholder="请选择" :form="form" :is-edit="form.id !== null" :is-clear="form.id !== null" key-value="branchComId" @change="changeProject" /> &ndash;&gt;-->
          <!--            </a-form-model-item>-->
          </a-col>

          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="会议名称："
              prop="meetingName"
            >
              <BaseInput
                v-model.trim="form.meetingName"
                :max-length="30"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="会议类型："
              prop="meetingKeyId"
            >
              <BSelect
                v-model="form.meetingKeyId"
                :request="meetingTypeListReq"
                @selectChange="form.meetingKeyName = $event.name"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="主持人/主讲人："
              prop="speaker"
            >
              <!-- <BaseInput :maxLength="30" placeholder="请输入" v-model.trim="form.speaker" /> -->
              <ASelectOrgPeople
                v-model="form.speaker"
                :org-id="projectDeptOrgId"
                option-key="id"
                :init="false"
                :show-search="true"
                placeholder="请选择"
              />
              <!-- <SelectPersonByProject :id="form.branchCompanyId" v-model="form.speaker" :project-id="form.projectId" :show-search="true" mode="combobox" placeholder="请选择" option-label-prop="children" /> -->
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="会议地点："
              prop="meetingPlace"
            >
              <BaseInput
                v-model.trim="form.meetingPlace"
                :max-length="300"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="会议时间："
              prop="startTime"
            >
              <a-date-picker
                v-model="form.startTime"
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                placeholder="请输入"
                @change="(date, dateString) => getTime(date, dateString, 'form', 'startTime')"
              />
            </a-form-model-item>
          </a-col>

          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="会议说明："
              prop="meetingExplains"
            >
              <BaseTextarea
                v-model.trim="form.meetingExplains"
                :max-length="300"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            v-if="false"
            span="24"
          >
            <a-form-model-item
              label="会议纪要"
              prop="meetingSummary"
            >
              <!-- <editor
                  v-model.trim="form.meetingSummary"
                  :isClear="true"
                   :maxLength="30000"
                  @change="commentsVal"
              ></editor> -->
              <BaseTextarea
                v-model="form.meetingSummary"
                :auto-size="{ minRows: 20, maxRows: 25 }"
                :max-length="30000"
                placeholder="加载中"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card class="mb20">
      <a-form-model
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row :gutter="24">
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="参会者选择："
              prop="meetingEmployeeDTOList"
            >
              <div class="mb12">
                <a-button
                  icon="plus"
                  class="btn_right"
                  type="primary"
                  @click="openSelectPersonModal"
                >
                  添加人员
                </a-button>
                <a-button
                  :disabled="rowSelection.selectedRowKeys.length < 1"
                  icon="delete"
                  type="danger"
                  @click="handleRemoveMore"
                >
                  移除
                </a-button>
              </div>
              <!-- 统计选中项 -->
              <a-alert :show-icon="true">
                <template slot="message">
                  <span style="margin-right: 12px">
                    已选择:
                    <a>
                      <b>{{ rowSelection.selectedRowKeys.length }}</b>
                    </a>
                    项
                  </span>
                </template>
              </a-alert>
              <!-- 表格 -->
              <s-table
                ref="tableEmployee"
                table-layout="fixed"
                size="default"
                row-key="id"
                :columns="columnsEmployee"
                :data="loadDataEmployee"
                :alert="true"
                :row-selection="rowSelection"
                show-size-changer
                show-quick-jumper
                show-pagination="auto"
              >
                <!-- 表格行操作栏 -->
                <span
                  slot="actions"
                  slot-scope="text, record, index"
                >
                  <template>
                    <a @click="handleRemove(index)">移除</a>
                  </template>
                </span>
              </s-table>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card
      v-if="form.value == '8' || form.value == '9'"
      class="mb20"
    >
      <titleName
        title="相关资料上传"
        class="title-style"
      />
      <div class="table-operator row">
        <l-table
          upload-type="normal"
          text="新增"
          btn-type="primary"
          :upload-arrys="form.fileList"
          business-code="SHE04"
          @fileArrysData="fileArrysData"
        />

        <!-- <a-button class="ml20">删除</a-button> -->
      </div>
      <s-table
        ref="table"
        size="default"
        row-key="key"
        :columns="columns"
        :data="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :show-pagination="false"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <span
          slot="action"
          slot-scope="text, record, index"
        >
          <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId">下载</a>
          <a-divider type="vertical" />
          <a
            href="javascript:"
            @click="$filePreview(record)"
          >预览</a>
          <a-divider type="vertical" />
          <a @click="delItem(index)">删除</a>
        </span>
      </s-table>
    </a-card>
    <div class="tool-btns page-btn-right-top">
      <a-button
        class="ml20"
        :loading="loading"
        type="primary"
        @click="addMeeting"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>

    <!-- 表单弹窗 -->
    <dialog-edit
      ref="dialogEdit"
      :meeting-employee-d-t-o-list-data="form.meetingEmployeeDTOListData"
      :visible.sync="visible"
      @confirm="submitForm"
      @confirms="submitForms"
    />
    <SelectPerson
      ref="SelectPersonWithTree"
      header-title="添加参会人员"
      :un-repeat-person="true"
      @confirm="submitForms"
    />
  </base-breadcrumb>
</template>
<script>
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
const columnsEmployee = [
  {
    title: '员工名称',
    dataIndex: 'name'
  },

  {
    title: '电话号码',
    dataIndex: 'phone'
  },

  {
    title: '操作',
    dataIndex: 'actions',
    width: '100px',
    scopedSlots: { customRender: 'actions' }
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
    width: '40%'
  },
  {
    title: '文件格式',
    dataIndex: 'suffixName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '10%',
    scopedSlots: { customRender: 'action' }
  }
]
import meetingTypeApi from '@/api/safetySupervision/base/meetingType.js'

import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import { STable } from '@/components'
import dialogEdit from '@/views/conference/standardConference/conferenceList/dialogEdit.vue'
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import SelectPerson from '@/components/BComponents/BSelectPerson'
import { getMeetingType, addMeeting, getConstructionProgram, getReviewPlan, getDisclosurePlan, getMeeting, editMeeting } from '@/api/office/conference'
import Vue from 'vue'

export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    STable,
    SelectSubcontractor,
    SelectPersonByProject,
    dialogEdit,
    SelectPerson,
    ASelectOrgPeople
  },
  data() {
    return {
      meetingTypeListReq: async () => {
        let res = await meetingTypeApi.list({}, { pageNo: 1, pageSize: 1000, query: { type: 12, enable: true } })
        if (res.code === this.SUCCESS_CODE) {
          res.data.map((v) => {
            v.disabled = v.enabled !== 'TRUE'
          })
          return { code: 200, data: res.data }
        }
        return { code: 200, data: [] }
      },
      columns,
      columnsEmployee,
      meetingType: false,
      token: Vue.getAcloudProvider().getAccessToken(),
      projectDeptOrgId: '', //项目所在的树节点Id
      form: {
        id: null,
        speaker: '',
        educationHour: '',
        educationResponsible: '',
        educationOrganization: '',
        value: 1,
        meetingSummary: '',
        fileList: [],
        meetingEmployeeDTOList: [],
        meetingEmployeeDTOListData: [],
        branchComId: '',
        projectId: '',
        name: '',
        meetingName: '',

        startTime: '',
        meetingExplains: '',
        commentedPlan: '',
        programmer: '',
        otherReviewer: '',
        professionComName: '',
        hsemonth: '',
        currentConstructionStage: '',
        meetingCount: '',
        mainParticipants: ''
      },
      rulesType: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],
        projectId: [{ required: true, message: '请选择项目' }],
        name: [{ required: true, message: '请输入名称' }]
      },
      rules: {
        meetingKeyId: [{ required: true, message: '请选择会议类型' }],
        month: [{ required: true, message: '请选择月份' }],
        commentedPlan: [{ required: true, message: '请选择交底方案', trigger: 'blur' }],
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        // projectId: '',
        meetingName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        speaker: [{ required: true, message: '请输入主持人/主讲人', trigger: 'blur' }],
        meetingPlace: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
        startTime: [{ required: true, message: '请输入会议时间', trigger: 'change' }],
        meetingExplains: [{ required: true, message: '请输入会议说明', trigger: 'blur' }]
      },
      rulesType1: {
        commentedPlan: [{ required: true, message: '请选择评审方案', trigger: 'blur' }],
        programmer: [{ required: true, message: '请选择方案编制人', trigger: 'blur' }],
        otherReviewer: [{ required: true, message: '请选择其他评审人员', trigger: 'blur' }]
      },
      rulesType2: {
        commentedPlan: [{ required: true, message: '请选择讲评方案', trigger: 'blur' }],
        programmer: [{ required: true, message: '请选择方案编制人', trigger: 'blur' }],
        professionComName: [{ required: true, message: '请选择专业单位名称', trigger: 'blur' }]
      },
      rulesType3: {
        hsemonth: [{ required: true, message: '请输入月份', trigger: 'change' }],
        currentConstructionStage: [{ required: true, message: '请输入当期施工阶段', trigger: 'blur' }]
      },
      rulesType5: {
        educationHour: [{ required: true, message: '请输入教育课时', trigger: 'blur' }],
        educationResponsible: [{ required: true, message: '请选择教育负责人', trigger: 'change' }],
        educationOrganization: [{ required: true, message: '请输入受教育单位', trigger: 'blur' }]
      },

      rulesType7: {
        commentedPlan: [{ required: true, message: '请选择交底方案', trigger: 'blur' }],
        // disclosurePlan: [{ required: true, message: '请输入交底方案', trigger: 'blur' }],
        meetingCount: [{ required: true, message: '请输入参会人数', trigger: 'blur' }],
        mainParticipants: [{ required: true, message: '请输入主要参会人员', trigger: 'blur' }]
      },

      rulesType8: {
        meetingCount: [{ required: true, message: '请输入参会人数', trigger: 'blur' }],
        mainParticipants: [{ required: true, message: '请输入主要参会人员', trigger: 'blur' }]
      },

      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.fileList
          })
        })
      },
      loadDataEmployee: (parameter) => {
        return new Promise((resolve, reject) => {
          let obj = {}
          obj.currentPage = parameter.pageNo
          obj.pageSize = parameter.pageSize
          obj.totalPage = Math.ceil(this.form.meetingEmployeeDTOListData.length / parameter.pageSize)
          obj.totalSize = this.form.meetingEmployeeDTOListData.length
          obj.data = this.form.meetingEmployeeDTOListData || []
          console.log(obj)
          resolve(obj)
        })
      },
      loading: false,
      id: '',
      isUpdate: true,
      meetingTypeList: [], //会议类别
      constructionProgram: [],
      reviewPlan: [],
      disclosurePlan: [],
      visible: false,
      // 表格复选框配置
      rowSelection: {
        selectedRowKeys: [],
        onChange(selectedRowKeys) {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      projectDeptOrgId: '' //项目所在的树节点Id
    }
  },
  mounted() {
    this.getMeetingType()
    if (this.$userInfo().currentPost.code == 'PD') {
      this.rules.projectId = [{ required: true, message: '请选择项目', trigger: 'blur' }]
    }
    if (this.$route.query.id) {
      this.form.id = this.$route.query.id
      this.getData()
    }
    if (this.$route.query.typeId) {
      this.form.value = this.$route.query.typeId
    }
  },
  methods: {
    selectOrg(val) {
      if(val&&val.length) {
        this.form.branchComId = val[val.length - 2].orgId
        this.projectDeptOrgId = this.form.branchComId
        this.form.speaker = ""
      }
    },
    async getData() {
      this.loading = true
      const [err, res] = await getMeeting({ id: this.form.id })
      this.loading = false
      if (!err) {
        this.form = { ...this.form, ...res.data }
        this.form.meetingEmployeeDTOListData = this.$clone(this.form.meetingEmployeeVOList)
        this.form.meetingEmployeeDTOListData.map((v) => (v.id = v.userId))
        this.$refs.tableEmployee.refresh(true)
      }
    },
    async getMeetingType() {
      const [err, res] = await getMeetingType()
      if (!err) {
        this.meetingTypeList = res.data
          .filter((v) => v.id !== '648785280249237505')
          .map((item) => {
            item.value = item.category
            item.label = item.name
            return item
          })
        console.log(this.meetingTypeList)
      }
    },
    openSelectPersonModal() {
      const list = this.form.meetingEmployeeDTOListData
      this.$refs.SelectPersonWithTree.open(list)
    },
    // 提交表单
    submitForm(e) {
      this.form.meetingEmployeeDTOListData.push(e)
      console.log(this.form.meetingEmployeeDTOListData)
      this.$refs.tableEmployee.refresh(true)
    },
    submitForms(e) {
      e.forEach((item) => {
        this.form.meetingEmployeeDTOListData.push(item)
      })
    },
    handleRemove(index) {
      this.form.meetingEmployeeDTOListData.splice(index, 1)
      this.$refs.tableEmployee.refresh(true)
    },
    // 移除表格选中项
    handleRemoveMore() {
      // 若有选中项
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定移除这些数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log(that.rowSelection.selectedRowKeys)
          for (let index = 0; index < that.form.meetingEmployeeDTOListData.length; index++) {
            let item = that.form.meetingEmployeeDTOListData[index]
            console.log(index, item.id)
            if (that.rowSelection.selectedRowKeys.includes(item.id)) {
              that.form.meetingEmployeeDTOListData.splice(index, 1)
              index--
            }
          }
          that.$refs.tableEmployee.clearSelected()
          that.$refs.tableEmployee.refresh(true)
          // console.log(that.rowSelection.selectedRowKeys)
        }
      })
    },
    getProjectInfo(id) {
      let params = {
        projectId: id
      }
      getProjectInfo(params).then((res) => {
        this.projectDeptOrgId = res.data.projectDeptOrgId
        // this.form.meetingEmployeeDTOListData = []
        // this.$refs.tableEmployee?.refresh(true)
        console.log(res)
      })
    },
    changeProject(e) {
      this.form.speaker = ''
      if (e) {
        this.getProjectInfo(e)
        this.getConstructionProgram(e) //获取专业分包
        this.getReviewPlan(e) //获取评审方案
        this.getDisclosurePlanReq(e)
      }
    },
    changeCommentedPlan(id) {
      console.log(this.constructionProgram)
      this.form.programmer = this.constructionProgram.filter((item) => this.form.commentedPlan == item.id)[0]?.creatorName
      if (this.form.value == 7) {
        this.form.meetingName = this.disclosurePlan.filter((item) => this.form.commentedPlan == item.id)[0].name + '交底会'
      }
      console.log(this.form)
    },
    changeReviewPlan(id) {
      this.form.programmer = this.reviewPlan.filter((item) => this.form.commentedPlan == item.id)[0].creatorName
    },
    async getReviewPlan(projectId) {
      const [err, res] = await getReviewPlan({ projectId: projectId, typeId: this.form.value })
      if (!err) {
        this.reviewPlan = res.data
      }
    },
    async getConstructionProgram(projectId) {
      const [err, res] = await getConstructionProgram({ projectId: projectId, typeId: this.form.value })
      if (!err) {
        this.constructionProgram = res.data
      }
    },
    async getDisclosurePlanReq(projectId) {
      const [err, res] = await getDisclosurePlan({ projectId: projectId, typeId: this.form.value })
      if (!err) {
        this.disclosurePlan = res.data
      }
    },
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
      console.log(this[type][name])
    },
    delItem(idx) {
      this.form.fileList.splice(idx, 1)
      this.$refs.table.refresh(true)
      console.log(this.form.fileList)
    },
    fileArrysData: function (val) {
      this.form.fileList = val
      this.$refs.table.refresh(true)
    },

    onChangeRadio(e) {
      console.log(e)
    },
    onChange(e) {
      console.log(e)
      // this.form.value = e.target.value
    },
    onSelectChange(e) {
      console.log('selectedRowKeys changed: ', e)
    },
    commentsVal: function (val) {
      console.log(val)
      this.form.meetingSummary = val
    },
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
      //  history.go(-1)
    },
    //基本会议
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((valid) => {
        flag = valid
        if(!valid) {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    //施工方案评审会议
    validateFormRule(rule) {
      let flagrule = true
      let flagbasis = false

      if (rule == 4 || rule == 6) {
        flagbasis = this.validateForm()
        return flagbasis
      } else {
        flagbasis = this.validateForm()
      }
      if (rule == 9) {
        rule = 8
      }
      let ruleForm = 'ruleForm' + rule
      console.log(ruleForm)
      this.$refs[ruleForm].validate((valid) => {
        flagrule = valid
      })

      if (flagrule && flagbasis) {
        return true
      } else {
        this.$message.warning('表单填写不完整')
        return false
      }
    },
    changeValue() {
      for (let i = 1; i < 8; i++) {
        if (i != 4 && i != 6) {
          let ruleForm = 'ruleForm' + i
          console.log(ruleForm)
          this.$refs[ruleForm].resetFields()
        }
      }
    },

    async addMeeting() {
      this.$console(this.form)
      const rule = this.form.value
      if (!this.validateForm()) return
      if (rule == 8 || rule == 9) {
        if (this.form.meetingSummary == '') {
          this.$message.warning('请填写会议纪要')
          return
        }
      } else {
        if (this.form.meetingEmployeeDTOListData.length == 0) {
          this.$message.warning('请选择参会人员')
          return
        }
      }
      this.form.meetingEmployeeDTOList = []
      this.form.meetingEmployeeDTOListData.forEach((item) => {
        this.form.meetingEmployeeDTOList.push(item.id)
      })
      const params = {
        ...this.form,
        meetingTypeId: this.meetingTypeList.filter((item) => this.form.value == item.category)[0].id
      }

      this.loading = true
      let err
      let res
      if (params.id) {
        ;[err, res] = await editMeeting(params)
      } else {
        ;[err, res] = await addMeeting(params)
      }
      this.loading = false
      if (!err) {
        this.$message.success('操作成功')
        this.handleClose()
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;

  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}

.row {
  display: flex;
  flex-direction: row;
}
</style>
